<?php

namespace App\Api\Controllers;

use App\Api\Services\AdminService;
use App\Api\Services\LoginService;
use App\Http\Controllers\Api\BaseController;
use App\Api\Models\AdminModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class AdminController extends BaseController
{
    /**
     * 子账号列列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 14:42
     * @return \Illuminate\Http\JsonResponse
     */
    public function userList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`页面大小`丢失',
            'pageSize.integer' => '参数`页面大小`仅能为数字',
            'currentPage.required' => '参数`当前页码`丢失',
            'currentPage.integer' => '参数`当前页码`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['keyword'] = empty($data['keyword'])?'':$data['keyword'];

        return $this->success(
            AdminService::userList($this->getMainUserId(), $data)
        );
    }

    /**
     * 转换子账号状态
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 16:14
     * @return \Illuminate\Http\JsonResponse
     */
    public function transStatus(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
            'status' => [
                'required',
                'integer',
                Rule::In([0,1]),
            ],//状态;1:启用;0:禁用;
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'status.required' => '参数`status`缺失',
                'status.integer' => '参数`status`只能为数字',
                'status.in' => '参数`status`不合法',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //检查子账户是否存在
        $checkUser = AdminService::checkUser($data['id']);

        if(!$checkUser) {
            return $this->fail('', '用户不存在');
        }

        Redis::SET('user_id_'.$data['id'].'_disabled', 1);
        AdminModel::where('id', $data['id'])->update(['is_active' => $data['status']]);
        $this->log('禁用子账号', $data);
        return $this->success();
    }

    /**
     * 审批人列表
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function approverList()
    {
        return $this->success(
            AdminService::approverList($this->getMainUserId())
        );
    }

    /**
     * 重置指定子账户登录密码
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 16:30
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPwd(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //检查子账户是否存在
        $checkUser = AdminService::checkUser($data['id']);

        if(!$checkUser) {
            return $this->fail('', '用户不存在');
        }

        if(AdminService::resetPwd($data)) {
            $this->log('重置指定子账号登录密码', $data);
            return $this->success();
        }
        else {
            return $this->fail('', '操作失败，请稍后再试');
        }
    }

    /**
     * 删除指定子账户
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/8 17:27
     * @return \Illuminate\Http\JsonResponse
     */
    public function delUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //检查子账户是否存在
        $checkUser = AdminService::checkUser($data['id']);

        if(!$checkUser) {
            return $this->fail('', '用户不存在');
        }

        AdminModel::where('id', $data['id'])->update(['delete_flag' => 1]);
        $this->log('删除指定子账号', $data);
        return $this->success();
    }

    /**
     * 新建子账号
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 11:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'username' => 'required',//用户id
            'nickname' => 'required',//用户id
            // 'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            'status' => [
                'required',
                'integer',
                Rule::In([0,1]),
            ],//状态;1:启用;0:禁用;
        ],
            [
                'username.required' => '参数`账号`缺失',
                'nickname.required' => '参数`子账号昵称`缺失',
                // 'mobile.regex' => '手机号格式错误，请重试',
                'status.required' => '参数`status`缺失',
                'status.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['mobile'])) {
            $checkMobile = Validator::make($data, [
                'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            ],
                [
                    'mobile.regex' => '手机号格式错误，请重试',
                ]
            );

            if ($infos = $checkMobile->errors()->first()) {
                return $this->fail('', $infos);
            }
        }

        $checkUser = AdminService::checUserInfo($this->getMainUserId(), $data);

        if(!$checkUser) {
            return $this->fail('', '账号已存在');
        }

        $result = AdminService::addUser($this->getMainUserId(), $data);

        return $this->success($result);
    }

    /**
     * 编辑指定子账号信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 13:52
     * @return \Illuminate\Http\JsonResponse
     */
    public function editUserInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
            'username' => 'required',//用户id
            'nickname' => 'required',//用户id
            'status' => [
                'required',
                'integer',
                Rule::In([0,1]),
            ],//状态;1:启用;0:禁用;
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'username.required' => '参数`账号`缺失',
                'nickname.required' => '参数`子账号昵称`缺失',
                'status.required' => '参数`status`缺失',
                'status.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['mobile'])) {
            $checkMobile = Validator::make($data, [
                'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            ],
                [
                    'mobile.regex' => '手机号格式错误，请重试',
                ]
            );

            if ($infos = $checkMobile->errors()->first()) {
                return $this->fail('', $infos);
            }
        }

        $checkUser = AdminModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if(empty($checkUser)) {
            return $this->fail('', '账号不存在');
        }

        $data['is_active'] = $data['status'];
        unset($data['status']);

        AdminModel::where('id', $data['id'])->update($data);

        $this->log('修改指定账号信息', $data);
        return $this->success();
    }

    /**
     * 设置子账号权限
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 15:42
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
            'first_module' => 'required',
            'second_module' => 'required',
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'first_module.required' => '参数`一级权限菜单模块`缺失',
                'second_module.required' => '参数`二级权限菜单模块`缺失',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('',$info);
        }

        $checkUser = AdminModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if(empty($checkUser)) {
            return $this->fail('', '账号不存在');
        }

        AdminModel::where('id', $data['id'])->update($data);
        Redis::SET('user_id_'.$data['id'].'_reset', 1);

        $this->log('修改子账号权限',$data);
        return $this->success();
    }

    /**
     * 获取子账号权限信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 16:08
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserPermission(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//用户id
        ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $userInfo = AdminModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if(empty($userInfo)) {
            return $this->fail('', '账号不存在');
        }

        $this->log('获取子账号可用权限信息', $data);
        return $this->success(AdminService::getUserPermission($this->getMainUserId(), $userInfo));
    }

    /**
     * 修改手机号-主账号
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 16:31
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function changeMobile(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'code' => 'required',//验证码
            'mobile' => 'required|regex:/^1[345789][0-9]{9}$/',
        ],
            [
                'code.required' => '参数`验证码`缺失',
                'mobile.required' => '手机号不能为空，请输入手机号',
                'mobile.regex' => '手机号格式错误，请重试',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!$this->getUserTpye()) {
            //比对用户输入的code和短信发送的code是否一致
            if(!Redis::exists($data['mobile'].'_mobile_login')) {
                return ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => ''];
            }
            else {
                if ($data['code'] == Redis::get($data['mobile'] . '_mobile_login')) {//验证码一致
                    $checkUserInfo = AdminModel::where('username', $data['mobile'])
                        ->where('parent_id', 0)
                        ->where('id', '!=', $this->getUserId())->first();

                    if (!empty($checkUserInfo)) {
                        return $this->fail('', '手机号已存在，无法重复使用');
                    } else {
                        AdminModel::changeMobile($this->getUserId(), $data);
                    }

                    Redis::del($data['mobile'] . '_mobile_login');//销毁验证信息
                    $this->log('修改手机号', $data);
                    return $this->success();
                } else {
                    return $this->fail('', '您输入的验证码有误，请重新输入');
                }
            }
        }
        else {
            return $this->fail('', '子账号无法完成此操作');
        }
    }

    /**
     * 修改用户信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/9 17:13
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyUserinfo(Request $request)
    {
        $data = $request->all();
        AdminModel::where('id', $this->getUserId())->update($data);
        $this->log('修改用户信息', $data);
        return $this->success();
    }

    /**
     * 子账号修改登录密码
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 10:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'old_pwd' => 'required',//旧密码
            'new_pwd' => 'required|min:6',//新密码
            'confirm_pwd' => 'required',//确认密码
        ],
            [
                'old_pwd.required' => '请输入旧密码',
                'new_pwd.required' => '请输入新密码',
                'new_pwd.min' => '密码最小长度为6位',
                'confirm_pwd.required' => '请输入确认密码',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if($data['new_pwd'] != $data['confirm_pwd']) {
            return $this->fail('', '两次输入的密码不一致，请重新输入');
        }

        $checkPwd = AdminService::checkPwd($this->getUserId(), $data);

        if(!$checkPwd) {
            return $this->fail('', '旧密码不正确,请重新输入');
        }

        AdminService::changePwd($this->getUserId(), $data);
        return $this->success();
    }

    /**
     * 个人中心
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 10:44
     * @return \Illuminate\Http\JsonResponse
     */
    public function userCenter()
    {
        return $this->success(
            AdminService::userCenter(
                $this->getUserId(),
                $this->getMainUserId()
            )
        );
    }

    /**
     * 解绑微信
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:01
     * @return \Illuminate\Http\JsonResponse
     */
    public function relieveWechatBind()
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        if(!empty($adminInfo['openid'])) {
            AdminModel::where('id', $this->getUserId())->update([
                'openid' => '',
                'wx_nickname' => ''
            ]);
        }
        else {
            return $this->fail('', '您当前还未绑定微信');
        }

        return $this->success();
    }

    /**
     * 微信绑定
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function wechatBind(Request $request)
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        $wxinfo = json_decode(LoginService::getOpenId($request->code), true);

        if(empty($adminInfo['openid']) && !empty($request->code)) {
            AdminModel::where('id', $this->getUserId())->update([
                'openid' => $wxinfo['openid'],
                'wx_nickname' => $request->nickname
            ]);
        }

        return $this->success();
    }

    /**
     * 获取被邀请人列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/10 11:17
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],
            [
                'pageSize.required' => '参数`pageSize`缺失',
                'pageSize.integer' => '参数`pageSize`只能为数字',
                'currentPage.required' => '参数`currentPage`缺失',
                'currentPage.integer' => '参数`currentPage`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info, 1);
        }

        if($this->getUserTpye() == 1) {
            return $this->fail('', '您的权限不足，无法查看被邀请人信息');
        }

        return $this->success(
            AdminService::inviteList(
                $this->getMainUserId(),
                $data
            )
        );
    }

    /**
     * 设置密码
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/14 13:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPwd(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'password' =>'required',//页面大小
            'confirm_pwd' =>['required', 'same:password'],//当前页
        ],
            [
                'password.required' => '请输入密码',
                'confirm_pwd.required' => '请输入确认密码',
                'confirm_pwd.same' => '两次密码不一致',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info, 1);
        }

        $data['id'] = $this->getUserId();

        $this->log('设置密码', $data);
        AdminService::setPwd($data);
        return $this->success();
    }

    /**
     * 转换出库方式
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/17 13:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function transOutWay()
    {
        return response()->json(
            AdminService::transOutWay($this->getMainUserId())
        );
    }
}
